package com.rfid.base.base;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.rfid.base.R;

public abstract class BaseFragment<T extends BasePresenter> extends BaseTitleFragment implements IView{

    protected T mPresenter;

    public abstract T getPresenter();

    AlertDialog mDialog;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mPresenter = getPresenter();
        if (mPresenter != null)
            mPresenter.onAttach(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (mPresenter != null) {
            mPresenter.detach();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(getLayoutResId(),container,false);
    }

    @Override
    public void onShowLoading(String msg) {
        Context context = getContext();
        if (context == null) {
            return;
        }
        if (mDialog != null) {
            mDialog.dismiss();
        }
        View view = LayoutInflater.from(context).inflate(R.layout.b_loading_layout,null);
        TextView textView = view.findViewById(R.id.loading_msg);
        if (TextUtils.isEmpty(msg)) {
            textView.setVisibility(View.GONE);
        } else {
            textView.setText(msg);
        }
        mDialog = new AlertDialog.Builder(getContext())
                .setView(view)
                .create();
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.show();
    }

    @Override
    public void onHideLoading() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }

    protected abstract int getLayoutResId();
}
